package com.huawei.quartz.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.quartz.bean.QuartzData;


import com.wjp.autoconfig.template.MyTemplate;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;

import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class MyQuartzJob implements Job {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MyTemplate myTemplate;

    @Override
    public void execute(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        logTasKDetail(context, jobDataMap, jobDetail);

        myTemplate.sayAge();
        myTemplate.sayHello();
    }

    private void logTasKDetail(JobExecutionContext context, JobDataMap jobDataMap, JobDetail jobDetail) {
        String quartzDataString = jobDataMap.getString("QuartzData");
        QuartzData quartzData;
        try {
            if (StringUtils.hasLength(quartzDataString)) {
                quartzData = objectMapper.readValue(quartzDataString, QuartzData.class);
            } else {
               quartzData = new QuartzData();
                quartzData.setExcuteCount(1);
                quartzData.setJobName(jobDetail.getKey().getName());
                quartzData.setTriggerName(context.getTrigger().getKey().getName());
            }
            quartzData.setExcuteTime(LocalDateTime.now());
            log.info("Quartz Job executed at {}, 上次执行时间为 {}", quartzData.getExcuteTime(),quartzData.getLastExcuteTime());
            log.info("Quartz Job executed JobName: {}, TriggerName: {}", quartzData.getJobName(), quartzData.getTriggerName());
            log.info("当前执行 {} 次", quartzData.getExcuteCount());
            quartzData.setExcuteCount(quartzData.getExcuteCount() + 1);
            quartzData.setLastExcuteTime(quartzData.getExcuteTime());
            jobDataMap.put("QuartzData", objectMapper.writeValueAsString(quartzData));
        } catch (JsonProcessingException e) {
            log.error("objectMapper readValue fail, errorMessage: {}", e.getMessage());
        }

    }
}
